<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/10
 * Time: 19:19
 */
namespace IDCU;
use Think\Controller as BaseController;

class Controller extends BaseController
{
    protected $pageKey = array('pageIndex','pageSize');

    protected $searchKey = 'select';

    protected $pageRule = array(1,20);

    protected $searchRule = array(
        'id'    =>  array('regex','exp','param1','param2')
    );

    protected $validateRule = array(

    );

    protected $modelName = CONTROLLER_NAME;

    public function __construct()
    {
        parent::__construct();
        $uid = session('authId');
        $switch = C('AUTOAUTH_ON');
        if($switch && $uid ==1) {
            $module = MODULE_NAME;
            $controller = CONTROLLER_NAME;
            $action = ACTION_NAME;
            $mid = $this->chckModule($module);
            $cid = $this->chckController($controller,$mid);
            $aid = $this->chckAction($action,$cid);
        }
    }
    public function chckAction($action,$pid){
        $has_action = M('Node')->where(array('name'=>$action,'pid'=>$pid))->find();
        if(!$has_action){
            $data['name'] = $action;
            $data['title'] = '自动生成'.$action;
            $data['status'] = 1;
            $data['sort'] = 1;
            $data['pid'] = $pid;
            $data['level'] = 3;
            $id = M('Node')->add($data);
        }else {
            $id = $has_action['id'];
        }
        return $id;
    }
    public function chckController($controller,$pid){
        $has_action = M('Node')->where(array('name'=>$controller,'pid'=>$pid))->find();
        if(!$has_action){
            $data['name'] = $controller;
            $data['title'] = '自动生成'.$controller;
            $data['status'] = 1;
            $data['sort'] = 1;
            $data['pid'] = $pid;
            $data['level'] = 2;
            $id = M('Node')->add($data);
        }else {
            $id = $has_action['id'];
        }
        return $id;
    }
    public function chckModule($module){
        $has_action = M('Node')->where(array('name'=>$module))->find();
        if(!$has_action){
            $data['name'] = $module;
            $data['title'] = '自动生成'.$module;
            $data['status'] = 1;
            $data['sort'] = 1;
            $data['pid'] = 0;
            $data['level'] = 1;
            $id = M('Node')->add($data);
        }else {
            $id = $has_action['id'];
        }
        return $id;
    }

    public function index(){
        $this->display();
    }

    public function create(){
        $this->display();
    }

    public function modify(){
        $this->display();
    }

    public function read(){
        $param = $this->getParam();
        if($param){
            $modelName = $this->modelName;
            $pk = D($modelName)->getPk();
            $field = array();
            $relation = array();
            if($param[$pk]){
                $data = D($modelName)->field($field)->relation($relation)->find($param[$pk]);
            }else{
                $data = D($modelName)->where($param)->field($field)->relation($relation)->find();
            }
            if($data){
                $res['stat'] = 1;
                $res['data'] = $data;
                $res['msg'] = '查找到1条数据。';
            }elseif($data == null){
                $res['stat'] = 0;
                $res['data'] = $data;
                $res['msg'] = '查找到0条数据。';
            }else{
                $res['stat'] = 0;
                $res['data'] = $data;
                $res['msg'] = '查找失败！';
            }
        }else{
            $res['stat'] = 0;
            $res['msg'] = '请提交参数！';
        }
        $this->ajaxReturn($res);
    }

    public function search(){
        $param = $this->getParam();
        $modelName = $this->modelName;
        $scope = array();
        $relation = array();
        $search = $this->getSearch();
        $page = $this->getPage();
        $data = D($modelName)->where($param)->where($search)->scope($scope)->relation($relation)->page($page[0],$page[1])->select();
        if($data){
            $res['stat'] = 1;
            $res['data'] = $data;
            $res['count'] = $data = D($modelName)->where($param)->where($search)->scope($scope)->count();
            $res['msg'] = '查找到1条数据。';
        }elseif($data == null){
            $res['stat'] = 1;
            $res['data'] = array();
            $res['count'] = 0;
            $res['msg'] = '查找到0条数据。';
        }else{
            $res['stat'] = 0;
            $res['data'] = $data;
            $res['msg'] = '查找失败！';
        }
        $res['recordsTotal'] = $res['count'];
        $res['recordsFiltered'] = $res['count'];
        $this->ajaxReturn($res);
    }

    public function add(){
        $param = $this->getParam();
        if($param){
            $modelName = $this->modelName;
            $field = array();
            $relation = array();
            $create = $field ? D($modelName)->field($field)->create($param,1) : D($modelName)->create($param,1);
            if($create){
                $data = D($modelName)->relation($relation)->add();
                if($data){
                    $pk = D($modelName)->getPk();
                    $res['stat'] = 1;
                    if($pk){
                        $res['pk'] = $data;
                    }
                    $res['data'] = $data;
                    $res['msg'] = '新增数据1条。';
                }else{
                    $res['stat'] = 0;
                    $res['msg'] = '新增数据失败！';
                }
            }else{
                $res['stat'] = 0;
                $res['msg'] = D($modelName)->getError();
            }
        }else{
            $res['stat'] = 0;
            $res['msg'] = '请提交参数！';
        }
        $this->ajaxReturn($res);
    }

    public function update(){
        $param = $this->getParam();
        if($param){
            $modelName = $this->modelName;
            $pk = D($modelName)->getPk();
            $field = array();
            $relation = array();
//            $where = array(); //自定义
            $create = $field ? D($modelName)->field($field)->create($param,2) : D($modelName)->create($param,2);
            if($create){
                if($param[$pk]){
                    $data = D($modelName)->relation($relation)->save();
                }else{
//                    $data = D($modelName)->where($where)->relation($relation)->save();
                }
                if($data){
                    $res['stat'] = 1;
                    $res['data'] = $data;
                    $res['msg'] = '更新数据成功。';
                }else{
                    $res['stat'] = 0;
                    $res['msg'] = '更新数据失败！';
                }
            }else{
                $res['stat'] = 0;
                $res['msg'] = D($modelName)->getError();
            }
        }else{
            $res['stat'] = 0;
            $res['msg'] = '请提交参数！';
        }
        $this->ajaxReturn($res);
    }

    public function delete(){
        $param = $this->getParam();
        if($param){
            $modelName = $this->modelName;
            $pk = D($modelName)->getPk();
            $relation = array();
            if($param[$pk]){
                $data = D($modelName)->relation($relation)->delete($param[$pk]);
            }else{
                foreach($param as $k=>$v){
                    $where[$k] = strToWhere($v);
                }
                $data = D($modelName)->where($where)->relation($relation)->delete();
            }
            if($data){
                $res['stat'] = 1;
                $res['data'] = $data;
                $res['msg'] = '删除数据'.$data.'条。';
            }else{
                $res['stat'] = 0;
                $res['msg'] = '删除数据失败！';
            }
        }else{
            $res['stat'] = 0;
            $res['msg'] = '请提交参数！';
        }
        $this->ajaxReturn($res);
    }

    public function validate(){
        $req = $this->getReq();
        $modelName = $this->modelName;
        $pk = D($modelName)->getPk();
        $param[$req['k']] = $req['v'];
        $rules = $this->validateRule;
        $param[$pk] = $req[$pk];
        $create = D($modelName)->validate($rules)->create($param);
        if($create){
            $res['stat'] = 1;
            $res['msg'] = '验证通过。';
        }else{
            $res['stat'] = 0;
            $res['msg'] = D($modelName)->getError();
        }
        $this->ajaxReturn($res);
    }

    //辅助方法，非接口
    protected function getReq(){
        $get = I('get.');
        $post = I('post.');
        $req = array_merge($get,$post);
        return $req;
    }

    public function getParam(){
        $req = $this->getReq();
        if($req){
            $modelName = $this->modelName;
            $param = D($modelName)->getParam($req);
        }
        return $param ? $param : array();
    }

    public function getPage(){
        $req = $this->getReq();
        if($req){
            $pageRule = $this->pageRule;
            $pageKey = $this->pageKey;
            foreach($pageKey as $k=>$v){
                $page[$k] = $req[$v] ? $req[$v] : $pageRule[$k];
            }
        }
        return $page;
    }

    public function getSearch($prefix=false){
        $req = $this->getReq();
        $searchKey = $this->searchKey;
        if(isset($req[$searchKey])){
            $searchRule = $this->searchRule;
            if(isset($req[$searchKey]) && $req[$searchKey]!==''){
                foreach($searchRule as $k=>$v){
                    $match = preg_match($v[0],$req[$searchKey]); //返回1或0
                    if($match){
                        switch($v[1])
                        {
                            case 'like':
                                $where[($prefix?$prefix:'').$k] = array($v[1],$v[2].$req[$searchKey].$v[3]);
                                break;
                            case 'eq':
                                $where[($prefix?$prefix:'').$k] = array($v[1],$req[$searchKey]);
                                break;
                            default:
                                $where[($prefix?$prefix:'').$k] = array($v[1],$req[$searchKey]);
                        }
                    }
                }
                if(count($where) > 1){
                    $where['_logic'] = 'or';
                    $search['_complex'] = $where;
                }elseif(count($where) == 1){
                    $search = $where;
                }
            }else{
                $search = array();
            }
        }else{
            $search = array();
        }
        return isset($search) ? $search : array('id'=>'xmj');
    }

    public function autoComplete(){
        $where['no'] = array('like',$this->getReq()['no'].'%');
        $where['status'] = array('neq',-1);
        $this->ajaxReturn(D($this->modelName)->where($where)->limit(5)->select());
    }
}